<template>
  <div>
    <el-dialog
      v-model="props.showDialog"
      :title="state.title"
      width="30%"
      :before-close="colseDialog"
    >
      <div class="form-box">
        <el-form ref="formRef" :model="formData" :rules="rules" class="demo-ruleForm">
          <el-form-item label="接口项目名称" prop="proName">
            <el-input v-model.number="formData.proName" type="text" autocomplete="off" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="colseDialog">取消</el-button>
          <el-button type="primary" @click="handleSave"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, watch, watchEffect, nextTick } from 'vue'
const formRef = ref(null)
const emit = defineEmits(['saveFormData', 'colseLog'])
const state = reactive({
  title: '添加项目'
})
const rules = {
  proName: [{ required: true, message: '请输入接口项目名称', trigger: 'blur' }]
}
let formData = reactive({
  proName: ''
})
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  projectObj: {
    type: Object,
    default: () => {}
  }
})
watch(
  () => props.projectObj,
  (newVal, oldVal) => {
    if (newVal?.id) {
      nextTick(() => {
        // formData = newVal
        formData = Object.assign(formData, newVal)
      })
      state.title = '修改项目'
    } else {
      state.title = '添加项目'
      // formData.proName = ''
    }
  }
)
//保存项目
function handleSave() {
  formRef.value.validate((valid) => {
    if (valid) {
      emit('saveFormData', formData)
      colseDialog()
    }
  })
}
//关闭
function colseDialog() {
  delete formData.id
  formRef.value.resetFields()

  emit('colseLog', false)
}
</script>
